from django.shortcuts import render, render_to_response
from django.http import HttpResponse, FileResponse
import os
import netifaces
import requests
from config import Config
from lib.stream import stream_media


def index(request):
    context = {
        'django_version': Config.DJANGO_VER,
    }
    return render(request, 'shark/index.html', context)


def ladder(request):
    os.environ["https_proxy"] = "http://127.0.0.1:1080"

    response = requests.get('https://api.vultr.com/v1/server/list', headers={'API-Key': Config.cru_info['vps_key']})
    res_dic = response.json()['26986794']
    context = dict()

    context['pending_charges'] = res_dic['pending_charges'] + '$'
    context['power_status'] = res_dic['power_status']
    context['server_state'] = res_dic['server_state']
    context['current_bandwidth'] = res_dic['current_bandwidth_gb']
    context['allowed_bandwidth'] = res_dic['allowed_bandwidth_gb']

    response = requests.get('https://api.vultr.com/v1/account/info', headers={'API-Key': Config.cru_info['vps_key']})
    context['balance'] = response.json()['balance'][1:] + '$'
    context['last_payment_date'] = response.json()['last_payment_date']

    context['major_ipv4'] = netifaces.ifaddresses("enp3s0f0")[netifaces.AF_INET][0]['addr']
    context['major_ipv6'] = Config.cru_info['major_ipv6']
    context['alt_ipv6'] = Config.cru_info['alt_ipv6']
    context['socksv4_port'] = Config.cru_info['socksv4_port']
    context['socksv6_port'] = Config.cru_info['socksv6_port']
    context['vps_ipv6'] = Config.cru_info['vps_ipv6']
    context['vps_port'] = Config.cru_info['vps_port']
    context['vps_password'] = Config.cru_info['vps_password']
    return render(request, 'shark/ladder.html', context)

def notfound(request):
    return render_to_response('404.html')


def src(request, *args):
    request_path = request.path.strip('/')
    local_path = os.path.join(Config.TEMP_SHARK, request_path)
    if local_path.endswith('.flac'):
        return stream_media(request, local_path)

    sending = open(os.path.join(Config.TEMP_SHARK, request_path), mode='rb')
    return FileResponse(sending)


def reconnect(request):
    os.system('/home/lrf/relog')
    return HttpResponse('OK')


def recsmonitor(request):
    os.system('python3 ' + os.path.join(Config.ROOT, 'getcsmonitor.py'))
    return HttpResponse('OK')